//Copyright (c) Microsoft Corporation.  All rights reserved.

using System;
using System.Diagnostics;

namespace Eas.WebCrawler.Common {
    /// <summary>This base class adds diagnostics to implementations of <see cref="IDisposable"/> that throws an assertion if the object is finalized.</summary>
    /// <remarks>In addition, this class checks (when in debug builds) that it is only disposed of once and it always (even non-debug builds) handles calling <see cref="GC.SuppressFinalize"/>.</remarks>
    public class BaseDisposable : IDisposable {
#if DEBUG
        int _DisposalCount;  //=0
#endif

        /// <summary>Finalizes this instance.</summary>
        ~BaseDisposable() { Dispose(false); }
        #region IDisposable Members

        /// <summary>Disposes this instance.</summary>
        public void Dispose() { Dispose(true); }

        #endregion


        /// <summary>Clean up resources of this object.</summary>
        /// <param name="isDisposing">Whether or not this object is being finalized.</param>
        protected virtual void Dispose(bool isDisposing) {
            if (isDisposing) {
                GC.SuppressFinalize(this);
#if DEBUG
                int disposalCount = System.Threading.Interlocked.Increment(ref _DisposalCount);
                System.Diagnostics.Debug.Assert(disposalCount == 1);
#endif
            }
            Debug.Assert(isDisposing);
        }
    }
}
